package util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dell on 2016-11-18 .
 */
public class Helper {
    public static int getIdFromRequest(HttpServletRequest request) {
        return getIdFromRequest(request, "id");
    }

    public static int getIdFromRequest(HttpServletRequest request, String fieldName) {
        String fieldPara = request.getParameter(fieldName);
        return Integer.parseInt(fieldPara);
    }

    /**
     * @param logicView 逻辑视图
     * @return 物理视图
     */
    public static String resolve(String logicView) {
        return "/WEB-INF/pages/" + logicView + ".jsp";
    }

    //为字串两端加引号
    public static String quote(String str) {
        return "\"" + str + "\"";
    }

    public static final String SING = "!@234%U?H23";

    public static String getToken(Map<String,String> map) {
        //添加Token过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        HashMap<String,Object> map1 =new HashMap<>();
        // 添加构成JWT的参数
        String token = JWT.create().withHeader(map1) //Header头信息
                .withClaim("username",map.get("username"))//payLoad荷载信息，实际数据
                .withClaim("password", map.get("password"))
                .withExpiresAt(instance.getTime())//令牌过期时间
                .sign(Algorithm.HMAC256(SING));//签名 由头信息+荷载信息+密钥 组合之后进行加密得到
        return token;
    }
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }


    public static void main(String[] args) {
        System.out.println(Helper.quote("schools:"));
    }
}
